package com.example.take_out_order.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.take_out_order.common.PageResult;
import com.example.take_out_order.common.lang.dto.OrdersCancelDTO;
import com.example.take_out_order.common.lang.dto.OrdersConfirmDTO;
import com.example.take_out_order.common.lang.dto.OrdersPageQueryDTO;
import com.example.take_out_order.common.lang.dto.OrdersRejectionDTO;
import com.example.take_out_order.common.lang.vo.OrderStatisticsVO;
import com.example.take_out_order.common.lang.vo.OrderVO;
import com.example.take_out_order.entity.Orders;
import com.example.take_out_order.exceptions.BusinessException;
import com.example.take_out_order.exceptions.enumetation.ResponseEnum;
import com.example.take_out_order.mapper.OrdersMapper;
import com.example.take_out_order.service.OrdersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author FZ
 * @since 2024-07-09
 */
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {

    @Resource
    private OrdersMapper ordersMapper;

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = ordersMapper.selectById(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = new Orders();
        orders.setId(ordersDB.getId());
        orders.setStatus(Orders.TO_BE_CONFIRMED);
        orders.setPayStatus(Orders.PAID);
        orders.setCheckoutTime(LocalDateTime.now());

    }

    /**
     * 订单搜索
     * @param source
     * @return
     */
    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO source) {
        final String[] dishName = {""};
        Page<OrderVO> page = new Page<>(source.getPage(),source.getPageSize());
        ordersMapper.conditionSearch(page, source);
        page.getRecords().forEach(s-> {
            s.getOrderDetailPOList().forEach(d-> {
                dishName[0] += d.getName() + "*" + d.getNumber() + ";";
            });
            s.setOrderDishes(dishName[0]);
        });

        return new PageResult(page.getTotal(),page.getRecords());
    }

    /**
     * 各个订单数量统计
     * @return
     */
    @Override
    public OrderStatisticsVO statistics() {
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setConfirmed((int)ordersMapper.selectList(new LambdaQueryWrapper<Orders>()
                .eq(Orders::getPayStatus, Orders.CONFIRMED)).stream().count());
        orderStatisticsVO.setToBeConfirmed((int)ordersMapper.selectList(new LambdaQueryWrapper<Orders>()
                .eq(Orders::getPayStatus,Orders.TO_BE_CONFIRMED)).stream().count());
        orderStatisticsVO.setDeliveryInProgress((int)ordersMapper.selectList(new LambdaQueryWrapper<Orders>()
                .eq(Orders::getPayStatus, Orders.DELIVERY_IN_PROGRESS)).stream().count());
        return orderStatisticsVO;
    }

    /**
     * 查询订单详情
     * @param id
     * @return
     */
    @Override
    public OrderVO detail(String id) {
        Orders orders = ordersMapper.selectById(id);
        OrderVO orderVO = new OrderVO();
        BeanUtil.copyProperties(orders, orderVO);
        return orderVO;
    }

    /**
     * 接单
     * @param source
     */
    @Override
    public void confirm(OrdersConfirmDTO source) {
        Orders Orders = ordersMapper.selectById(source.getId());
        Orders.setStatus(Orders.CONFIRMED);
        ordersMapper.updateById(Orders);
    }

    /**
     * 拒单
     * @param source
     */
    @Override
    public void rejection(OrdersRejectionDTO source) {
        Orders Orders = ordersMapper.selectById(source.getId());
        //订单只有存在且状态为2(待接单)才可以拒单
        if(ObjUtil.isNull(Orders) || !Orders.getStatus().equals(Orders.TO_BE_CONFIRMED)){
            throw new BusinessException(ResponseEnum.ORDER_STATUS_ERROR);
        }
        //退款
        //拒单
        Orders.setStatus(Orders.CANCELLED);
        Orders.setRejectionReason(source.getRejectionReason());
        Orders.setCancelReason(source.getRejectionReason());
        Orders.setCancelTime(LocalDateTime.now());
        ordersMapper.updateById(Orders);
    }

    /**
     *
     * @param source
     */
    @Override
    public void cancel(OrdersCancelDTO source) {
        Orders Orders = ordersMapper.selectById(source.getId());
        Orders.setStatus(Orders.CANCELLED);
        Orders.setCancelReason(source.getCancelReason());
        Orders.setCancelTime(LocalDateTime.now());
        ordersMapper.updateById(Orders);
    }

    /**
     * 派送订单
     * @param id
     */
    @Override
    public void delivery(String id) {
        Orders Orders = ordersMapper.selectById(id);
        //检验订单是否存在并且状态为 3
        if (ObjUtil.isNull(Orders) || !Orders.getStatus().equals(Orders.CONFIRMED)){
            throw new BusinessException(ResponseEnum.ORDER_STATUS_ERROR);
        }
        //更新订单状态,转为派送中
        Orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        ordersMapper.updateById(Orders);
    }

    @Override
    public void complete(String id) {
        Orders Orders = ordersMapper.selectById(id);
        //检查订单是否存在并且状态为4
        if (ObjUtil.isNull(Orders) || !Orders.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)){
            throw new BusinessException(ResponseEnum.ORDER_STATUS_ERROR);
        }
        //更新订单状态,转为已完成
        Orders.setStatus(Orders.COMPLETED);
        Orders.setDeliveryTime(LocalDateTime.now());
        ordersMapper.updateById(Orders);
    }
}
